;(function() {
  new Vue({
    el: '#floor-plan',
    data: {
      floorId: null,
      buildId: null,
      projectId: window.localStorage.getItem('projectId'),
      floorData: [],
      buildData: [],
      unitData: {
        units: []
      },
      postData: {
        floor_id: null,
        plain_graph: null,
        units: [],
        unitsY: []
      },
      imageUrl: '',
      configState: '',
      saveId: [],
      delId: null,
      delInx: null,
      imgIndex: null,
      baseWidth:null,
      baseHeight:null,
      naturalWidth:null,
      naturalHeight:null,
      scale:0.1,
      addNum:0
    },
    filters: {
      unitType: function(str) {
        var result = '';
        switch (str) {
          case 'BU':
            result = '普通'
            break;
          case 'ST':
            result = '车位'
            break;
          case 'WP':
            result = '工位'
            break;
        }
        return result
      }
    },
    computed: {
      locateTypeY: function() {
        var result = 0;
        this.unitData.units.map(function(item) {
          if (item.locateType === 'Y') {
            result++;
          }
        })
        return result
      },
      locateTypeN: function() {
        var result = 0;
        this.unitData.units.map(function(item) {
          if (item.locateType === 'N') {
            result++;
          }
        })
        return result
      }
    },
    methods: {
      //点击下一步
      nextPage: function () {
        var _this = this;
        hlhttp.put({
          url: 'check_project_config',
          data: {project_id: hlUrlUtil.GetQueryString('projectId')},
          success: function (data) {
            window.sessionStorage.setItem('NAVPOSTION', 4)
            $('.js-nav-btn li').eq(4).trigger('click')
          },
          error: function (xhr, type) {
            hl.toast('项目没有配置完成')
          }
        })
      },
      //重置
      resetDB: function () {
        this.floorId = null;
        this.buildId = null;
        this.floorData = [];
        this.buildData = [];
        this.unitData = {units: []}
        this.postData = {floor_id: null,plain_graph: null,units: []};
        this.imageUrl = '';
        this.configState = '';
        this.saveId = [];
        this.$refs.buildName.innerHTML = '请选择楼栋'
        this.$refs.floorName.innerHTML = '请选择楼层'
      },
      //取消选中
      cancelSelect: function () {
        var _this = this;
        document.onclick = function (e) {
          $('.drag-drop').removeClass('can-drop')
          e.stopPropagation()
        }
      },
      //选中删除定位
      delIndexp: function (id, index, e) {
        this.delId = id;
        this.delInx = index;
        $(e.srcElement).addClass('can-drop').siblings().removeClass('can-drop')
        e.stopPropagation()
        return false;
      },
      delPos: function () {
        var _this = this;
        if (!this.delId) {
          hl.toast('请先点击要删除的颜色块')
          return
        }
        hllayer.confirm('是否确认删除单元定位？', function () {
          hlhttp.delete({
            url: 'unit_locate?unit_id=' + _this.delId,
            success: function () {
              hl.toast('删除成功')
              _this.delId = null;
              _this.unitData.units[_this.delInx].locateType = 'N'
              for (var i = 0; i < _this.saveId.length; i++) {
                if (_this.saveId[i] == _this.delId) {
                  _this.saveId.splice(i, 1);
                  break
                }
              }
            }
          })
        }, function () {
          _this.delId = null;
          $('.hllayer-view,.hllayer-mask').remove()
        })
      },
      //删除平面图
      delpmt: function () {
        var _this = this;
        hllayer.confirm('删除平面图后，所有单元定位会被删除，是否确认删除？', function () {
          hlhttp.delete({
            url: 'floors/plain_graph?floor_id=' + _this.floorId,
            success: function () {
              hl.toast('删除成功')
              _this.getUnit(_this.floorId)
            }
          })
        })
      },
      //获取楼宇楼层
      getFloor: function() {
        var _this = this;
        hlhttp.get({
          url: 'project/buildings',
          data: {
            project_id: hlUrlUtil.GetQueryString('projectId') || '#'
          },
          success: function(res) {
            _this.floorData = res
          }
        })
        this.projectId=hlUrlUtil.GetQueryString('projectId');
      },
      //获取楼层
      getBuild: function(id) {
        // 如果重复点击同一栋楼 则返回处理
        if(this.buildId == id) return false;

        var _this = this;
        this.buildId = id;
        this.floorId = null;
        hlhttp.get({
          url: 'building/floors',
          data: {
            project_id: _this.projectId,
            building_id: id
          },
          success: function(res) {
            _this.buildData = res;
            _this.unitData = {units: []};
            _this.$refs.floorName.innerHTML = '请选择楼层'
            _this.imageUrl = null;
          }
        })
      },
      //获取楼层单元列表
      getUnit: function(id, url, state, index) {
        // 如果重复点击同一栋楼的同一楼层  则返回处理
        if(this.floorId == id) return false;

        this.floorId = id;
        this.imageUrl = url;
        this.configState = state;
        this.imgIndex = index;

        var _this = this;
        hlhttp.get({
          url: 'floor/units,acerage',
          data: {
            project_id: _this.projectId,
            floor_id: id,
            building_id: _this.buildId
          },
          success: function(res) {
            _this.unitData = res;
            _this.addNum = 0;
            _this.baseWidth = null;
            _this.baseHeight = null;
            _this.naturalWidth = null;
            _this.naturalHeight = null;

            $('.floor-image').css('width','945')
            $('.floor-image').css('height','auto')
          }
        })
      },
      //变绿
      changeGreen: function (i) {
        if (!this.imageUrl) {
          hl.toast('请先上传平面图')
          return
        }
        var unitWidth = 100;
        var unitHeight = 100;
        var scrollTop = $('#container').scrollTop()
        var scrollLeft = $('#container').scrollLeft()

        this.unitData.units[i].locateType = 'Y';
        this.unitData.units[i].paddingLeft = parseInt(945/2 + scrollLeft - unitWidth/2);
        this.unitData.units[i].paddingTop = parseInt(388/2 + scrollTop - unitHeight/2);
        this.unitData.units[i].width = unitWidth.toString();
        this.unitData.units[i].height = unitHeight.toString();
        this.saveId.push(this.unitData.units[i].unitId)
      },
      //保存当前楼层配置
      saveFloor: function () {
        this.postData.units = [];

        var rate = 1 + this.addNum * this.scale;
        var div = document.querySelectorAll('.drag-drop');
        for (var i = 0; i < this.saveId.length; i++) {
          if (this.saveId[i] == this.saveId[i+1]) {
            this.saveId.splice(i,1);
            i--;
          }
        }

        for (var i = 0; i < div.length; i++) {
          var width = parseFloat(div[i].style.width) / rate + '';
          var height = parseFloat(div[i].style.height) / rate + '';
          var paddingTop = parseFloat(div[i].getAttribute('data-y')) / rate + '';
          var paddingLeft = parseFloat(div[i].getAttribute('data-x')) / rate + '';

          if (this.saveId.indexOf(div[i].getAttribute('data-id')) > -1) {
            this.postData.units.push({
              unit_id: div[i].getAttribute('data-id'),
              paddingTop: paddingTop,
              paddingLeft: paddingLeft,
              width: width,
              height: height,
              color: 'rgba(239,106,122,0.9)'
            })
          }
        }

        var _this = this;
        if (!this.postData.units) {
          hl.toast('不能为空')
          return
        }
        hlhttp.post({
          url: 'floors/plain_graph',
          data: {
            floor_id: _this.floorId,
            plain_graph: _this.imageUrl,
            units: JSON.stringify(_this.postData.units)
          },
          success: function () {
            hl.toast('保存成功')
            if (_this.imgIndex) {
              _this.buildData[_this.imgIndex].plainGraph = _this.imageUrl
            }
          }
        })
      },
      initDrag: function() {
        var _this = this;
        function dragMoveListener(event) {
          var target = event.target;
          // keep the dragged position in the data-x/data-y attributes
          x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,
          y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;

          // translate the element
          target.style.webkitTransform = target.style.transform = 'translate(' + x + 'px, ' + y + 'px)';
          // update the posiion attributes
          target.setAttribute('data-x', x);
          target.setAttribute('data-y', y);
        }

        interact('.dropzone')
        .dropzone({
          // only accept elements matching this CSS selector
          accept: '.drag-drop',
          // 限制元素多少比例时进入指定范围算进入
          overlap: 1,
          // listen for drop related events:
          // 拖动开始时事件
          ondropactivate: function(event) {
            // add active dropzone feedback
            event.target.classList.add('drop-active');
          },
          // 拖拽进入指定范围
          ondragenter: function(event) {
            var draggableElement = event.relatedTarget,
              dropzoneElement = event.target;
            // feedback the possibility of a drop
            dropzoneElement.classList.add('drop-target');
            draggableElement.classList.add('can-drop');
          },
          // 拖拽出范围
          ondragleave: function(event) {
            // remove the drop feedback style
            event.target.classList.remove('drop-target');
            event.relatedTarget.classList.remove('can-drop');
          },
          // 拖动结束时事件
          ondropdeactivate: function(event) {
            // remove active dropzone feedback
            event.relatedTarget.setAttribute('data-drap', 'Y')
            event.relatedTarget.classList.remove('can-drop');
            _this.saveId.push(event.relatedTarget.getAttribute('data-id'))
          }
        })

        interact('.drag-drop')
        .draggable({
          // 每次拖拽移动时调用
          onmove: dragMoveListener,
          // 限制元素在其父元素区域内移动
          restrict: {
            restriction: 'parent',
            elementRect: {
              top: 0,
              left: 0,
              bottom: 1,
              right: 1
            }
          }
        })
        .resizable({
          // 调整大小边缘设置
          edges: {
            left: true,
            right: true,
            bottom: true,
            top: true
          },

          // 限制调整的最大边缘在父元素内
          restrictEdges: {
            outer: 'parent',
            endOnly: true
          },

          // minimum size
          restrictSize: {
            min: { width: 10, height: 10 },
          },


          inertia: true
        })
        .on('resizemove', function(event) {
          var target = event.target,
              x = (parseFloat(target.getAttribute('data-x')) || 0),
              y = (parseFloat(target.getAttribute('data-y')) || 0);

          // update the element's style
          target.style.width  = event.rect.width + 'px';
          target.style.height = event.rect.height + 'px';

          // translate when resizing from top or left edges
          x += event.deltaRect.left;
          y += event.deltaRect.top;

          target.style.webkitTransform = target.style.transform =
              'translate(' + x + 'px,' + y + 'px)';

          target.setAttribute('data-x', x);
          target.setAttribute('data-y', y);
          target.setAttribute('data-width', event.rect.width);
          target.setAttribute('data-height', event.rect.height);
        })
        .on('resizeend', function (event) {
          var target = event.target;
          _this.saveId.push(target.getAttribute('data-id'))
        })

      },
      // 放大缩小时 同比例更新方块大小
      updateSize:function(director){
        var originRate = director == 'add' ? (1 + (this.addNum - 1) * this.scale) : (1 + (this.addNum + 1) * this.scale);
        var rate = 1 + this.addNum * this.scale;

        $('.drag-drop').each(function(_index,_item){
          // 单元比例为1时的基准尺寸为：

          var baseWidth = $(_item).attr('data-width') / originRate
          var baseHeight = $(_item).attr('data-height') / originRate
          var basePadTop = $(_item).attr('data-y') / originRate
          var basePadLeft = $(_item).attr('data-x') / originRate
          var obj = {
            'width':baseWidth * rate,
            'height':baseHeight * rate,
            'paddingTop':basePadTop * rate,
            'paddingLeft':basePadLeft * rate
          }

          $(_item)
          .css({
            'width':obj.width,
            'height':obj.height,
            'transform':'translate('+ obj.paddingLeft + 'px,' + obj.paddingTop + 'px)'
          })
          .attr('data-x',obj.paddingLeft)
          .attr('data-y',obj.paddingTop)
          .attr('data-width',obj.width)
          .attr('data-height',obj.height)
        })
      },
      // 平面图图形数据
      isIncreaseOrDecreaseFLoorPlan:function(director){
        var self = this;
        var isChangeSize = function(){
          var imageWidth = $('.floor-image').width();
          var maxWidth = self.naturalWidth;
          if(imageWidth >= maxWidth && director == 'add'){
            hl.toast('平面图已放大至最大值')
            return false;
          }

          var minWidth = self.naturalWidth < self.baseWidth ? self.naturalWidth : self.baseWidth
          if(imageWidth <= minWidth && director == 'reduce'){
            hl.toast('平面图已缩小至最小值')
            return false;
          }
          return true
        }

        if(this.baseWidth){
          return isChangeSize()
        }
        if(!this.baseWidth){
          var imgEle = document.querySelector('.floor-image');
          self.baseWidth = $('.floor-image').width();
          self.baseHeight = $('.floor-image').height();
          self.naturalWidth = imgEle.naturalWidth;
          self.naturalHeight = imgEle.naturalHeight;
          return isChangeSize()
        }

      },
      // 放大平面图
      increaseFloorPlan:function(){
        var self = this;
        if(self.isIncreaseOrDecreaseFLoorPlan('add')){
          self.addNum++;
          $('.floor-image').css('width',self.baseWidth * (1 + self.addNum * self.scale))
          $('.floor-image').css('height',self.baseHeight * (1 + self.addNum * self.scale))
          $('#outer-dropzone').css('width',self.baseWidth * (1 + self.addNum * self.scale))
          self.updateSize('add')
        }
      },
      // 缩小平面图
      decreaseFloorPlan:function(){
        var self = this;
        if(self.isIncreaseOrDecreaseFLoorPlan('reduce')){
          self.addNum--;
          $('.floor-image').css('width',self.baseWidth * (1 + self.addNum * self.scale))
          $('.floor-image').css('height',self.baseHeight * (1 + self.addNum * self.scale))
          self.updateSize('reduce')
        }
      }
    },
		created () {
			hlSelectUi()
		},
    mounted: function() {
			this.getFloor()
      this.cancelSelect()
      this.initDrag();
    }
  })
}())
